package com.sjk.kafka.kafka;

import cn.hutool.core.date.DateTime;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.db.DaoTemplate;
import com.alibaba.fastjson.JSON;
import com.bw.springboot.stater.email.bean.MailBean;
import com.bw.springboot.stater.email.service.MailService;
import com.sjk.kafka.entity.Rizhi;
import com.sjk.kafka.entity.TCar;
import com.sjk.kafka.service.IRizhiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class KafkaDao{
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    IRizhiService iRizhiService;
    @Autowired
    KafkaTemplate kafkaTemplate;
    @Autowired
    MailService mailService;
    @KafkaListener(topics = {"123456"})
    public void kafka(String msg){
        TCar tCar = JSON.parseObject(msg, TCar.class);
        String s = SecureUtil.md5(JSON.toJSONString(tCar));
        Rizhi rizhi = new Rizhi();
        rizhi.setCount(JSON.toJSONString(tCar));
        rizhi.setTime(new Date());
        iRizhiService.save(rizhi);
        try {
            if (!redisTemplate.opsForValue().setIfAbsent(s,null,60, TimeUnit.SECONDS)){
                log.info("重复添加");
                return;
            }
            MailBean mailBean = new MailBean();
            mailBean.setContent("添加新车");
            mailBean.setSubject("添加新车");
            mailBean.setRecipient("1085730469@qq.com");
            mailService.sendSimpleMail(mailBean);
            return;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("发送消息失败，再来一次");
            MailBean mailBean = new MailBean();
            mailBean.setContent("添加新车");
            mailBean.setSubject("添加新车");
            mailBean.setRecipient("1085730469@qq.com");
            mailService.sendSimpleMail(mailBean);
            return;


//            if (!redisTemplate.opsForValue().setIfAbsent(s,null,60, TimeUnit.SECONDS)){
//
//            }
//            Object o = redisTemplate.opsForValue().get(s + "000");
//            int count = o==null?0:(int)o;
//            if (count>2){
//                log.info("重复三次没有发送成功");
//                return;
//            }
//            log.info("count是{}",count);
//            redisTemplate.opsForValue().set(s+"000",count+1);
//            kafkaTemplate.send("123456",JSON.toJSONString(tCar));
        }
    }
}
